﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.AutoCAD.ApplicationServices;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// 文档集的扩展
    /// </summary>
    public static class DocumentCollectionExtention
    {
        private static Dictionary<string, EventObject> events = new Dictionary<string, EventObject>();
        /// <summary>
        /// 添加设置的事件，设置所有的文档和未来添加到app的文档，执行一次文档的相关函数（本意是为每个<see cref="Document"/>添加面板事件）
        /// </summary>
        /// <param name="docs">文档集</param>
        /// <param name="eventName">事件名称</param>
        /// <param name="addEvent">添加事件（本意是添加事件）</param>
        /// <param name="removeEvent">移除事件（本意是添加事件）</param>
        public static void SetDocumentEvent(this DocumentCollection docs, string eventName, Action<Document> addEvent, Action<Document> removeEvent)
        {
            events.Add(eventName, new EventObject() { AddEvent = addEvent, RemoveEvent = removeEvent });
            docs.AddDocumentEvent(eventName);
        }

        /// <summary>
        /// 添加设置的事件
        /// </summary>
        /// <param name="docs">文档集</param>
        /// <param name="eventName">事件名称</param>
        public static void AddDocumentEvent(this DocumentCollection docs, string eventName)
        {
            EventObject e = events[eventName];
            if (e.IsConnect)
                return;
            e.IsConnect = true;

            // 所有的现有文档，执行添加面板事件
            foreach (Document doc in docs.Cast<Document>())
            {
                e.AddEvent?.Invoke(doc);
            }

            // 让未来添加到app的文档，执行添加面板事件
            docs.DocumentCreated += e.DocumentCreatedEvent;
        }

        /// <summary>
        /// 移除设置的事件
        /// </summary>
        /// <param name="docs">文档集</param>
        /// <param name="eventName">事件名称</param>
        public static void RemoveDocumentEvent(this DocumentCollection docs, string eventName)
        {
            EventObject e = events[eventName];
            if (!e.IsConnect)
                return;
            e.IsConnect = false;

            // 所有的现有文档，执行移除面板事件
            foreach (Document doc in docs.Cast<Document>())
            {
                e.RemoveEvent?.Invoke(doc);
            }

            // 让未来添加到app的文档，执行移除面板事件
            docs.DocumentCreated -= e.DocumentCreatedEvent;
        }


        private class EventObject
        {
            public EventObject()
            {
                DocumentCreatedEvent = (sender, e) =>
                {
                    AddEvent?.Invoke(e.Document);
                };
            }

            public Action<Document> AddEvent { get; set; }

            public Action<Document> RemoveEvent { get; set; }

            /// <summary>
            /// 未来添加到app的文档的事件,
            /// </summary>
            public DocumentCollectionEventHandler DocumentCreatedEvent { get; }

            public bool IsConnect { get; set; } = false;
        }
    }
}
